package br.rnp.linkcrawler;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;

public class LinkParserCallback extends ParserCallback {
	private List<URL> links = new ArrayList<URL>();
	private final URL url;

	public LinkParserCallback(URL url) {
		this.url = url;
	}

	@Override
	public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
		super.handleStartTag(t, a, pos);
		if (t == Tag.A) {
			if (a == null || a.getAttribute(Attribute.HREF) == null){
				return;
			}
			try {
				String href = a.getAttribute(Attribute.HREF).toString();
				if (!href.startsWith(url.getProtocol()) && !href.startsWith("/")) {
					href = "/" + href;
				}
				if (href.startsWith(url.getProtocol())) {
					links.add(new URL(href));
				} else {
					links.add(new URL(url.getProtocol() + "://" + url.getHost()
							+ ((url.getPort() == -1) ? "" : ":" + url.getPort())
							+ href));
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				System.out.println("npe");
			}
		}
	}

	public List<URL> getLinks() {
		return links;
	}
}
